<?php
/**
 * Created by PhpStorm.
 * User: Janderson
 * Date: 02/12/2014
 * Time: 14:10
 */

namespace helpers;


trait CsvHelper {

    public function csvExport($rs, $name="export"){
        $export = array();

        $this->exportKeys($rs, $export);
        $this->exportValues($rs, $export);

        if(count($export) > 0){
            header('Content-Type: text/csv; charset=utf-8');
            header("Content-Disposition: attachment; filename=$name.csv");
            $csv = fopen("php://output", "w");
            foreach($export as $item){
                if(!empty($item)){
                    $item = array_map("utf8_encode", $item);
                    fputcsv($csv, $item, ';', '"');
                }
            }
            fclose($csv);
        }
    }

    private function exportKeys($rs, &$export){
        $chaves = array();
        foreach($rs as $key => $value){
            foreach($value as $k => $v){
                $chaves[] = $k;
            }
            $export[] = $chaves;
            break;
        }
    }

    private function exportValues($rs, &$export){
        $valores = array();
        foreach($rs as $value){
            foreach($value as $k => $v){
                $valores[] = $this->noAccentuation($v);
            }
            $export[] = $valores;
            $valores = array();
        }
    }

} 